
<script lang="ts">
import { useUser } from '@/store';
import * as api from "@/api";
import { I_CourseRes } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
interface I_State {
    courseData: I_CourseRes[];
    search: string;
    tempForm: I_CourseRes;
    isOpenChangeInfoDialog: boolean;
    pages: {
        currentPage: number;
        pageSize: number;
        total: number;
    };
    isOpenAddCourseDialog: boolean;
}
export default defineComponent({
    setup() {
        const userStore = useUser();
        const { user } = storeToRefs(userStore);
        const router = useRouter();
        const state = reactive<I_State>({
            courseData: [],
            tempForm: {
                id: 0,
                name: '',
                number: "",
                credit: 0,
            },
            pages: {
                currentPage: 1,
                pageSize: 10,
                total: 10,
            },
            search: "",
            isOpenChangeInfoDialog: false,
            isOpenAddCourseDialog: false,
        });
        onMounted(() => {
            api.course.getAllCourseInformation({ index: state.pages.currentPage, size: state.pages.pageSize }).then(res => {
                state.courseData = res.records;
                state.pages.total = res.total;
            }).catch(err => {
                router.replace('/login');
            });
        });
        let timer: any;
        watch([() => state.search], () => {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            timer = setTimeout(() => {
                api.course.getCourseData({ search: state.search, index: state.pages.currentPage, size: state.pages.pageSize }).then(res => {
                    state.courseData = res.records;
                    state.pages.total = res.total;
                }).catch(err => {
                    router.replace('/login');
                });
                timer = null;
            }, 500);
        });
        const courseFormRef = ref<FormInstance>();
        const courseAddFormRef = ref<FormInstance>();
        const openChangeInfoDialog = (data: I_CourseRes) => {
            state.isOpenChangeInfoDialog = true;
            state.tempForm = { ...data };
        };
        const deleteCourse = (data: I_CourseRes) => {
            api.course.deleteCourseInformation({ id: data.id }).then(res => {
                api.course.getAllCourseInformation({ index: state.pages.currentPage, size: state.pages.pageSize }).then(res => {
                    state.courseData = res.records;
                    state.pages.total = res.total;
                }).catch(err => {
                    router.replace('/login');
                });
            });
        };
        const closeChangeInfoDialog = () => {
            state.isOpenChangeInfoDialog = false;
            state.tempForm = {
                id: 0,
                name: '',
                number: "",
                credit: 0,
            };
        };
        const updateCourse = async (formEl: FormInstance | undefined) => {
            if (!formEl) return;
            await formEl.validate((valid, fields) => {
                if (valid) {
                    api.course.updateCourseInformation(state.tempForm).then(res => {
                        closeChangeInfoDialog();
                        api.course.getCourseData({
                            search: state.search,
                            index: state.pages.currentPage,
                            size: state.pages.pageSize,
                        }).then(res => {
                            state.courseData = res.records;
                            state.pages.total = res.total;
                        }).catch(err => {
                            router.replace('/login');
                        });
                    });
                }
            });
        };
        const courseRules = reactive<FormRules>({
            number: [
                { required: true, message: "请输入用户名", trigger: "blur" },
                { min: 11, max: 11, message: "长度必须为11个字符", trigger: "blur" },
            ],
            name: [
                { required: true, message: "请输入课程名", trigger: "blur" },
                { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
            ],
            credit: [
                { required: true, message: "请输入学分", trigger: "blur" },
                { required: true, message: "类型必须为数字", trigger: "blur", type: 'number' },
            ],
        });
        const handleSizeChange = (val: number) => {
            state.pages.pageSize = val;
            api.course.getCourseData({ search: state.search, index: state.pages.currentPage, size: state.pages.pageSize }).then(res => {
                state.courseData = res.records;
                state.pages.total = res.total;
            });
        };
        const handleCurrentChange = (val: number) => {
            state.pages.currentPage = val;
            api.course.getCourseData({ search: state.search, index: state.pages.currentPage, size: state.pages.pageSize }).then(res => {
                state.courseData = res.records;
                state.pages.total = res.total;
            });
        };
        const openAddInfoDialog = () => {
            state.isOpenAddCourseDialog = true;
            state.tempForm = {
                id: 0,
                name: '',
                number: "",
                credit: 0,
            };
        };

        const closeAddInfoDialog = () => {
            state.isOpenAddCourseDialog = false;
            state.tempForm = {
                id: 0,
                name: '',
                number: "",
                credit: 0,
            };
        };
        const addCourse = async (formEl: FormInstance | undefined) => {
            if (!formEl) return;
            await formEl.validate((valid, fields) => {
                if (valid) {
                    api.course.addCourseData(state.tempForm).then(res => {
                        closeAddInfoDialog();
                        api.course.getAllCourseInformation({
                            index: state.pages.currentPage,
                            size: state.pages.pageSize,
                        }).then(res => {
                            state.courseData = res.records;
                            state.pages.total = res.total;
                        }).catch(err => {
                            router.replace('/login');
                        });
                    });
                }
            });
        };
        return {
            user,
            courseRules,
            closeChangeInfoDialog,
            openChangeInfoDialog,
            updateCourse,
            deleteCourse,
            courseFormRef,
            courseAddFormRef,
            handleSizeChange,
            openAddInfoDialog,
            addCourse,

            closeAddInfoDialog,
            handleCurrentChange,
            ...toRefs(state)
        };
    }
});
</script>
<template>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ name: 'r_welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>课程管理</el-breadcrumb-item>
        <el-breadcrumb-item>课程信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="overflow: auto">
        <el-table :data="courseData" border style="width: 100%">
            <el-table-column prop="number" label="课程代码" width="180" align="center" />
            <el-table-column prop="name" label="课程名" align="center" />
            <el-table-column prop="credit" label="学分" width="180" align="center" />
            <el-table-column fixed="right" label="操作" width="220" align="center">
                <template #header>
                    <el-input v-model="search" size="large" placeholder="请输入课程代码或课程名..." clearable />
                </template>
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="openChangeInfoDialog(scope.row)">修改</el-button>
                    <el-button link type="primary" size="small" @click="deleteCourse(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row style="margin-top:10px;">
            <el-col :span="22">
                <el-pagination background layout="total,sizes,prev, pager, next" :total="pages.total"
                    :page-sizes="[3, 5, 10, 20]" :page-size="pages.pageSize" @size-change="handleSizeChange"
                    :current-page="pages.currentPage" @current-change="handleCurrentChange"></el-pagination>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" style="float:right;" @click="openAddInfoDialog">新增</el-button>
            </el-col>
        </el-row>

    </el-card>
    <!-- 更新 -->
    <el-dialog v-model="isOpenChangeInfoDialog" :title="`更新用户信息(当前角色:${user.role})`">
        <el-form :model="tempForm" ref="courseFormRef" :rules="courseRules">
            <el-form-item label="课程代码" prop="number" :label-width="100">
                <el-input v-model="tempForm!.number" clearable placeholder="请输入课程代码" />
            </el-form-item>
            <el-form-item label="课程名" prop="name" :label-width="100">
                <el-input v-model="tempForm!.name" clearable placeholder="请输入课程名" />
            </el-form-item>

            <el-form-item label="学分" prop="credit" :label-width="100">
                <el-input v-model.number="tempForm!.credit" clearable placeholder="请输入学分" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeChangeInfoDialog">取消</el-button>
                <el-button type="primary" @click="updateCourse(courseFormRef)">
                    更新
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog v-model="isOpenAddCourseDialog" :title="`添加用户信息(当前角色:${user.role})`">
        <el-form :model="tempForm" ref="courseAddFormRef" :rules="courseRules">
            <el-form-item label="课程代码" prop="number" :label-width="100">
                <el-input v-model="tempForm!.number" clearable placeholder="请输入课程代码" />
            </el-form-item>
            <el-form-item label="课程名" prop="name" :label-width="100">
                <el-input v-model="tempForm!.name" clearable placeholder="请输入课程名" />
            </el-form-item>
            <el-form-item label="学分" prop="credit" :label-width="100">
                <el-input v-model.number="tempForm!.credit" clearable placeholder="请输入学分" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeAddInfoDialog">取消</el-button>
                <el-button type="primary" @click="addCourse(courseAddFormRef)">
                    添加
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<style lang = "less" scoped>

</style>